<template>
    <el-form ref="ruleFormRef" label-position="top" :model="form" :rules="formRules" label-width="auto"
        v-loading="isLoading">
        <el-row :gutter="30">
            <re-col :value='24' :xs='24' :sm='24'>
                <el-form-item prop='file'>
                    <el-upload class="upload-demo" drag accept=".xlsx" :auto-upload="false" multiple :limit="1"
                        :style="{ width: '100%' }" :on-change="handleChange" v-model:file-list="uploadFiles">
                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">
                            拖拽文件或者<em>点击文件</em>上传
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                <!-- jpg/png files with a size less than 500kb -->
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </re-col>
            <!-- <re-col :value='24' :xs='24' :sm='24'>
                <el-form-item :label='titles?.modelInfo' prop='modelInfo'>
                    <div class="w-full flex-bc gap-[10px]">
                        <el-select v-model="form.factoryId" :placeholder="prompt.factoryId"
                            :style="{ width: '100%' }" @change="form.productId = null; form.modelId = null">
                            <el-option v-for="item in factoryList" :key="item.value" :label="item.factoryName"
                                :value="item.factoryId" />
                        </el-select>
                        <el-select v-model="form.productId" :placeholder="prompt.productId"
                            :style="{ width: '100%' }" @change="form.modelId = null">
                            <el-option v-for="item in productList" :key="item.value" :label="item.productName"
                                :value="item.productId" />
                        </el-select>
                        <el-select v-model="form.modelId" :placeholder="prompt.modelId"
                            :style="{ width: '100%' }">
                            <el-option v-for="item in modelList" :key="item.value" :label="item.modelName"
                                :value="item.modelId" />
                        </el-select>
                    </div>
                </el-form-item>
            </re-col>
            <re-col :value='12' :xs='24' :sm='24'>
                <el-form-item :label='titles?.unityId' prop='unityId'>
                    <unitParentSelect v-model='form.unityId' clearable :style="{ width: '100%' }"
                        :placeholder='prompt?.unityId' @blur="formValidateField(ruleFormRef, 'unityId')"/>
                </el-form-item>
            </re-col>
			<re-col :value='12' :xs='24' :sm='24'>
				<el-form-item :label='titles?.expireDate' prop='expireDate'>
					<el-date-picker :style="{ width: '100%' }" v-model="form.expireDate" clearable type="date"
						:placeholder='prompt?.expireDate' format="YYYY-MM-DD"
						value-format="YYYY-MM-DD" />
				</el-form-item>
			</re-col>
            <re-col :value='12' :xs='24' :sm='24'>
                <el-form-item :label='titles?.superviseUnityIds' prop='superviseUnityIds'>
                    <superviseUnitySelect v-model='form.superviseUnityIds' clearable multiple
                        :placeholder='prompt?.superviseUnityIds' :style="{ width: '100%' }" @blur="formValidateField(ruleFormRef, 'superviseUnityIds')"/>
                </el-form-item>
            </re-col> -->
        </el-row>
    </el-form>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import ReCol from "@/components/ReCol";
import type { FormRules } from "element-plus";
import { titles, prompt } from './index';
import type { infoType } from '@/api/manage/resource-management/serial-number-management/index';
import type { CascaderProps } from 'element-plus'
import { getProductTypeSelectList, getProductModelSelectList } from '@/api/manage/resource-management/serial-number-management/index';
import { getFactorySelectList } from '@/api/manage/product-management/product-type/index'
import superviseUnitySelect from '@/components/select/superviseUnitySelect/superviseUnitySelect.vue'
import unitParentSelect from '@/components/select/unitParentSelect/unitParentSelectTree.vue'
import { formValidateField } from '@/utils/functions'
type FormProps = {
    form: any,
    isLoading: boolean,
}

const props = withDefaults(defineProps<FormProps>(), {
    form: () => ({} as infoType),
    isLoading: false,
});

const factoryList = ref([])
const productList = ref([])
const modelList = ref([])
const formRules = reactive(<FormRules>{
    modelInfo: [{ required: true, message: prompt?.modelInfo, trigger: 'blur' },
    {
        validator: (rule, value, callback) => {
            if (!props.form.factoryId) {
                callback(new Error('请选择厂家'));
            } else if (!props.form.productId) {
                callback(new Error('请选择产品类型'));
            } else if (!props.form.modelId) {
                callback(new Error('请选择产品型号'));
            } else {
                callback();
            }
        }
    }
    ],
    unityId: [{ required: true, message: prompt?.unityId, trigger: 'blur' },],
    superviseUnityIds: [{ required: false, message: prompt?.superviseUnityIds, trigger: 'blur' },],
    expireDate: [{ required: true, message: prompt?.expireDate, trigger: 'blur' },],
    file: [{ required: true, message: '请上传文件', trigger: 'blur' },],
});
const ruleFormRef = ref();
const cascaderOptions = ref([]);
const cascaderKey = ref(0)
const cascaderProps: CascaderProps = {
    lazy: true,
    lazyLoad(node, resolve) {
        const { level } = node
        if (level == 0) {
            // getFactorySelectList().then(res => {
            // 	let nodes = res.result.map((item) => ({
            // 		value: item.factoryId,
            // 		label: item.factoryName,
            // 	}))
            // 	resolve(nodes)
            // })
            resolve(null)
        } else if (level == 1) {
            getProductTypeSelectList({ factoryId: node.value }).then(res => {
                let nodes = res.result.map((item) => ({
                    value: item.productId,
                    label: item.productName,
                }))
                resolve(nodes)
            })
        } else if (level == 2) {
            getProductModelSelectList({ productId: node.value }).then(res => {
                let nodes = res.result.map((item) => ({
                    value: item.modelId,
                    label: item.modelName,
                    leaf: true
                }))
                resolve(nodes)
            })
        }
    },
}
const uploadFiles = ref<any>([])
    getFactorySelectList().then(res => {
	factoryList.value = res.result
})
watch(() => props.form.factoryId, () => {
	if (!props.form.factoryId) return;
	getProductTypeSelectList({ factoryId: props.form.factoryId }).then(res => {
		productList.value = res.result
	})
}, {
	immediate: true,
	deep: true
})
watch(() => props.form.productId, () => {
	if (!props.form.productId) return;
	getProductModelSelectList({ productId: props.form.productId }).then(res => {
		modelList.value = res.result
	})
}, {
	immediate: true,
	deep: true
})
const handleChange = (uploadFile, uploadFiles) => {
    console.log('handleChange', uploadFile, uploadFiles);
    props.form.file = uploadFile.raw
}
const cascaderDataChange = (e) => {
    if (e?.length == 3) {
        props.form.factoryId = e[0]
        props.form.productId = e[1]
        props.form.modelId = e[2]
    } else {
        props.form.factoryId = null
        props.form.productId = null
        props.form.modelId = null
    }
}

const loadCascaderOptions = () => {
    getFactorySelectList().then(res => {
        let nodes = res.result.map((item) => ({
            value: item.factoryId,
            label: item.factoryName,
            children: [],
        }))
        if (props.form?.modelInfo) {
            nodes.forEach((item) => {
                if (item.value == props.form?.modelInfo[0]) {
                    getProductTypeSelectList({ factoryId: item.value }).then(res => {
                        let nodes1 = res.result.map((item1) => ({
                            value: item1.productId,
                            label: item1.productName,
                            children: [],
                        }))
                        nodes1.forEach((item2) => {
                            if (item2.value == props.form?.modelInfo[1]) {
                                getProductModelSelectList({ productId: item2.value }).then(res => {
                                    let nodes2 = res.result.map((item3) => ({
                                        value: item3.modelId,
                                        label: item3.modelName,
                                        leaf: true
                                    }))
                                    item2.children = nodes2
                                    cascaderKey.value++
                                })
                            }
                        })
                        item.children = nodes1
                    })
                }
            })
        }
        cascaderOptions.value = nodes
    })
}

function getRef() {
    return ruleFormRef.value;
}

defineExpose({ getRef, loadCascaderOptions });
</script>
